#include <stdio.h>
#include <cstdlib>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>  //mysql的客户端头文件


int main()
{
    //1. 初始化MYSQL结构体
    MYSQL conn;
    MYSQL * pconn = mysql_init(&conn);
    printf("&conn: %p, pconn:%p\n\n", &conn, pconn);
    //2. 连接数据库
    const char * host = "localhost";
    const char * user = "root";
    const char * passwd = "1234";
    const char * db = "3th";
    pconn = mysql_real_connect(&conn, host, user, passwd,db, 0, NULL, 0);
    if(!pconn) {
        fprintf(stderr, "%s\n", mysql_error(&conn));
        return EXIT_FAILURE;
    }

    //3. 执行查询, 读操作
    const char * sql = "select * from student";
    int ret = mysql_real_query(pconn, sql, strlen(sql));
    if(ret != 0) {
        fprintf(stderr, "ERROR %d : %s\n", 
                mysql_errno(pconn),
                mysql_error(pconn));
        return EXIT_FAILURE;
    }

    //4.获取查询的结果集
    MYSQL_RES * result = mysql_store_result(pconn);
    if(result) {
        int cols = mysql_num_fields(result);
        int rows = mysql_num_rows(result);//从打印结果来看，为8
        printf("result: (%d, %d)\n", rows, cols);

        //打印所有的字段名
        MYSQL_FIELD * parr = mysql_fetch_fields(result);
        for(int i = 0; i < cols; ++i) {
            printf("%s\t", parr[i].name);
        }
        printf("\n");
        
        //打印所有的每一行的数据
        MYSQL_ROW row;
        while((row= mysql_fetch_row(result)) != nullptr) {
            for(int i = 0; i < cols; ++i) {
                printf("%s\t", row[i]);
            }
            printf("\n");
        }

    } else {
        //未查询到

    }
    //5. 释放结果集
    mysql_free_result(result);
    //6. 关闭连接
    mysql_close(pconn);

    return 0;
}

